package com.cn.yugan.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.os.Bundle;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.TextView;
import android.widget.Toast;


import com.carlos.notificatoinbutton.library.NotificationButton;
import com.cn.yugan.Cons.ArticleConstants;
import com.cn.yugan.Engine.Adapter.FragmentAdapter;
import com.cn.yugan.Cons.LoginConstants;
import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Engine.Http.Cookies;
import com.cn.yugan.Engine.Http.GetRespInfo;
import com.cn.yugan.Engine.Http.LoadUserface;
import com.cn.yugan.Engine.Http.Nocation;
import com.cn.yugan.Engine.Json.NoticeNormalMessageJsonObj;
import com.cn.yugan.Fragment.IndexFragment;

import com.cn.yugan.Utils.GsonUtils;
import com.cn.yugan.Utils.ImgUtils;
import com.cn.yugan.mobile.R;

import com.cn.yugan.Utils.LogUtils;
import com.cn.yugan.Utils.StringConv;
import com.cn.yugan.Utils.ToastUtils;
import com.cn.yugan.Widget.YGSpinner.AbstractSpinerAdapter;
import com.cn.yugan.Widget.YGSpinner.SpinerPopWindow;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Rover on 2016/7/17 .
 * Email 357319517@qq.com
 * 主页面
 */

public class IndexActivity extends FragmentActivity implements View.OnClickListener, AbstractSpinerAdapter.IOnItemSelectListener {
    private DrawerLayout mDrawerLayout;
    private NavigationView navigationView;
    private ImageView userimg;
    private NotificationButton usermessage;
    private TextView usersign, username;
    private LinearLayout tagsll;
    // private ProgressBar userexp;
    private ImageView abuserimg;
    private TextView abusername;
    private ImageView absearch;
    // 以下为viewpage所用到的变量
    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private FragmentAdapter mFragmentAdapter;
    private ViewPager mPageVp;
    //tab内的textview
    private TextView mtaboriTV, mtabpolTV, mtabgameTV, mtabanimTV, mtabelTV;
    //导引线
    private ImageView mTabLineIv;
    //各类fragment
    private IndexFragment manimFragment;
    private IndexFragment mgameFragment;
    private IndexFragment mpolFragment;
    private IndexFragment melFragment;
    private IndexFragment moriFragment;

    //vp选中页
    private int currentIndex;
    //屏宽
    private int screenWidth;
    private long mExitTime;
    private int LoginMode;


    //spiner
    private TextView mTView;
    private List<String> sortlist = new ArrayList<String>();
    private SpinerPopWindow mSpinerPopWindow;
    private String SortMode = ArticleConstants.time;
    //Sp
    private SharedPreferences sp;
    public static IndexActivity instance = null;
    //
    private Drawable duserimg;

    //flags
    private boolean IsReloadUserInfo = false;
    
    
    //Receiver
    private MyNoticeReceiver receiver=null;
    private AsyncHttpClient asyncHttpClient;
    
     Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Nocation.NOTICE_ALL:
                    int i = ((NoticeNormalMessageJsonObj) (msg.obj)).getUnread();
                    usermessage.setNotificationNumber(i);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        //设置静态变量，方便关闭该activity
        instance = this;

//        CircularImage circularImage = (CircularImage) findViewById(R.id.cover_user_photo);
//        circularImage.setImageResource(R.mipmap.default_img);
        initmode();
        init();
        initTabLineWidth();
        setupViews();
        setupReceiver();
    }

    

    //双返回退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再次点击返回键退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initmode() {
        Intent intent = getIntent();
        LoginMode = intent.getIntExtra("LoginMode", LoginConstants.LOGIN_GUEST);
    }

    private void setupViews() {
        mTView = (TextView) findViewById(R.id.index_sort_tv);
        mTView.setOnClickListener(this);
        String[] sorts = getResources().getStringArray(R.array.sortmode);
        for (int i = 0; i < sorts.length; i++) {
            sortlist.add(sorts[i]);
        }
        mSpinerPopWindow = new SpinerPopWindow(this);
        mSpinerPopWindow.refreshData(sortlist, 0);
        mSpinerPopWindow.setItemListener(this);
    }

    private void showSpinWindow() {
        Log.e("", "showSpinWindow");
        mSpinerPopWindow.setWidth(mTView.getWidth());
        mSpinerPopWindow.showAsDropDown(mTView);
    }

    @Override
    public void onItemClick(int pos) {
        if (pos >= 0 && pos <= sortlist.size()) {
            String value = sortlist.get(pos);
            switch (value) {
                case "最新发布":
                    SortMode = ArticleConstants.time;
                    refreshCurrectItem();
                    break;
                case "热门评论":
                    SortMode = ArticleConstants.comment;
                    refreshCurrectItem();
                    break;
                case "最新评论":
                    SortMode = ArticleConstants.commenttime;
                    refreshCurrectItem();
                    break;
                case "点击最多":
                    SortMode = ArticleConstants.click;
                    refreshCurrectItem();
                    break;
            }
            mTView.setText(value);
        }
    }

    private void init() {
        asyncHttpClient = new AsyncHttpClient(true,80,443);
        asyncHttpClient.addHeader("cookie", AddReqCookie.getNormalheader(this));
        
        sp = getSharedPreferences("Session", MODE_PRIVATE);
        //actionbar
        abuserimg = (ImageView) findViewById(R.id.index_userimg_cover);
        abusername = (TextView) findViewById(R.id.index_username);
        absearch = (ImageView) findViewById(R.id.index_search_iv);

        abusername.setText(GetRespInfo.getusername(IndexActivity.this));


        abuserimg.setOnClickListener(this);
        abusername.setOnClickListener(this);
        absearch.setOnClickListener(this);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.index_dl_left);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(new NacigateonItemSelectedLinstener());

        //侧滑菜单
        View view = navigationView.inflateHeaderView(R.layout.nav_header_main);
        userimg = (ImageView) view.findViewById(R.id.cover_user_photo);
        usermessage = (NotificationButton) view.findViewById(R.id.left_message);
        tagsll = (LinearLayout) view.findViewById(R.id.left_tags_ll);
//        userexp = (ProgressBar) view.findViewById(R.id.left_pb);
        usermessage.setNotificationNumber(3);
        usersign = (TextView) view.findViewById(R.id.user_sign);
        username = (TextView) view.findViewById(R.id.left_username);


        username.setText(GetRespInfo.getusername(IndexActivity.this));

        userimg.setOnClickListener(this);
        usermessage.setOnClickListener(this);


        getuserinfo();
        getnotice();

        if (LoginMode == LoginConstants.LOGIN_GUEST) {
            tagsll.setVisibility(View.INVISIBLE);
//            userexp.setVisibility(View.INVISIBLE);
            username.setVisibility(View.INVISIBLE);
            usermessage.setVisibility(View.INVISIBLE);
            usersign.setText("请登录！");
            usersign.setTextSize(16);
            abusername.setText("游客");
        } else if (LoginMode == LoginConstants.LOGIN_NORMAL) {

        }
        //VP相关
        mtabpolTV = (TextView) this.findViewById(R.id.id_pol_tv);
        mtaboriTV = (TextView) this.findViewById(R.id.id_ori_tv);
        mtabgameTV = (TextView) this.findViewById(R.id.id_game_tv);
        mtabanimTV = (TextView) this.findViewById(R.id.id_anim_tv);
        mtabelTV = (TextView) this.findViewById(R.id.id_el_tv);

        mtaboriTV.setOnClickListener(this);
        mtabpolTV.setOnClickListener(this);
        mtabgameTV.setOnClickListener(this);
        mtabanimTV.setOnClickListener(this);
        mtabelTV.setOnClickListener(this);

        resetTextView();
        mtabpolTV.setTextColor(Color.WHITE);

        mTabLineIv = (ImageView) this.findViewById(R.id.index_tab_line_iv);
        mPageVp = (ViewPager) this.findViewById(R.id.index_frame);

        manimFragment = new IndexFragment(IndexActivity.this, "3", SortMode);
        melFragment = new IndexFragment(IndexActivity.this, "4", SortMode);
        moriFragment = new IndexFragment(IndexActivity.this, "1", SortMode);
        mpolFragment = new IndexFragment(IndexActivity.this, "0", SortMode);
        mgameFragment = new IndexFragment(IndexActivity.this, "2", SortMode);


        manimFragment.setLoginMode(LoginMode);
        melFragment.setLoginMode(LoginMode);
        moriFragment.setLoginMode(LoginMode);
        mpolFragment.setLoginMode(LoginMode);
        mgameFragment.setLoginMode(LoginMode);
        mFragmentList.add(mpolFragment);
        mFragmentList.add(moriFragment);
        mFragmentList.add(mgameFragment);
        mFragmentList.add(manimFragment);
        mFragmentList.add(melFragment);


        mFragmentAdapter = new FragmentAdapter(this.getSupportFragmentManager(), mFragmentList);
        mPageVp.setAdapter(mFragmentAdapter);
        mPageVp.setCurrentItem(0);
        mPageVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            /**
             * state滑动中的状态 有三种状态（0，1，2） 1：正在滑动 2：滑动完毕 0：什么都没做。 
             */
            @Override
            public void onPageScrollStateChanged(int state) {

            }

            /**
             * position :当前页面，及你点击滑动的页面 offset:当前页面偏移的百分比 
             * offsetPixels:当前页面偏移的像素位置 
             */
            @Override
            public void onPageScrolled(int position, float offset,
                                       int offsetPixels) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
                        .getLayoutParams();

                Log.e("offset:", offset + "");
                /**
                 * 利用currentIndex(当前所在页面)和position(下一个页面)以及offset来 
                 * 设置mTabLineIv的左边距 滑动场景：
                 *
                 */

                if (currentIndex - 1 == position) {
                    lp.leftMargin = (int) (-(1 - offset) * (screenWidth * 1.0 / 5) + currentIndex * (screenWidth / 5));
                } else if (currentIndex == position) {
                    lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 5) + currentIndex * (screenWidth / 5));

                }
                mTabLineIv.setLayoutParams(lp);

            }

            @Override
            public void onPageSelected(int position) {
                resetTextView();
                switch (position) {
                    case 0:
                        mtabpolTV.setTextColor(Color.WHITE);
                        break;
                    case 1:
                        mtaboriTV.setTextColor(Color.WHITE);
                        break;
                    case 2:
                        mtabgameTV.setTextColor(Color.WHITE);
                        break;
                    case 3:
                        mtabanimTV.setTextColor(Color.WHITE);
                        break;
                    case 4:
                        mtabelTV.setTextColor(Color.WHITE);
                        break;
                }
                currentIndex = position;
                refreshCurrectItem();
            }
        });

    }

    private void getuserinfo() {
        String url = getString(R.string.serverurl) + getString(R.string.getinfos);
        RequestParams requestParams = new RequestParams();
        String uid = sp.getString("uid", null);
        uid = uid.substring(uid.indexOf("=") + 1, uid.indexOf(";"));
        requestParams.put("uid", uid);
        requestParams.put("names[0]", "username");
        requestParams.put("names[1]", "img");
        requestParams.put("names[2]", "regtime");
        requestParams.put("names[3]", "tags");
        requestParams.put("names[4]", "intro");
        asyncHttpClient.post(this, url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    new Cookies(IndexActivity.this, headers);
                    LogUtils.d(new String(bytes, "UTF-8"));
                    JSONObject jsonObject = new JSONObject(StringConv.Unicode2UTF8(new String(bytes, "UTF-8")));
                    jsonObject = jsonObject.getJSONObject("data");
                    String url = getString(R.string.imgserverurl) + jsonObject.getString("img").replace("?", "!userface75?"); //+ "imageView2/1/w/75/h/75:";
                    LogUtils.d(url);
                    ImageView[] img = new ImageView[]{userimg, abuserimg};
                    LoadUserface.getUserface(IndexActivity.this, url, img, null);
                    LogUtils.d("头像加载");
                    //简介加载
                    usersign.setText(jsonObject.getString("intro"));
                    //将信息存入sp中
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("regtime", jsonObject.getString("regtime"));
                    editor.putString("img", jsonObject.getString("img"));
                    editor.putString("tags", jsonObject.getString("tags"));
                    editor.putString("intro", jsonObject.getString("intro"));
                    editor.putString("tags", jsonObject.getString("tags"));
                    editor.commit();
                    //tags的显示
                    /**
                     *  android:layout_width="25dp"
                     android:layout_height="25dp"
                     android:background="@drawable/bg_tv_lv"
                     android:text="测试位置"
                     android:textColor="@android:color/white"
                     android:textSize="10dp" />
                     */
                    tagsll.removeAllViews();
                    String tags = jsonObject.getString("tags");
                    if (!"null".equals(tags) && tags != null && tags != "") {
                        String[] tagstr = tags.split(" ");
                        LogUtils.d(tagstr[0]);
                        int count = 0;
                        for (String str : tagstr) {
                            count++;
                            TextView textView = new TextView(IndexActivity.this);
                            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            textView.setBackground(getResources().getDrawable(R.drawable.bg_tv_lv));
                            textView.setTextColor(Color.WHITE);
                            textView.setTextSize(10);
                            textView.setGravity(Gravity.CENTER);
                            textView.setPadding(10, 10, 10, 10);
                            String[] info = str.split(":");
                            if (count == 4) {
                                textView.setText("...");
                                break;
                            }
                            if (info[0].matches("[0-9]+")) {
                                textView.setText(info[1]);
                            } else {
                                textView.setText(info[0]);
                            }
                            LogUtils.d(info[1]);
                            tagsll.addView(textView);
                        }
                    }
                    LogUtils.d(sp.getString("regtime", ""));
                    LogUtils.d(sp.getString("img", ""));
                    LogUtils.d(sp.getString("tags", ""));
                    LogUtils.d(sp.getString("intro", ""));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                ToastUtils.show(IndexActivity.this, "数据获取错误");
                try {
                    LogUtils.d(new String(bytes, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 设置滑动条的宽度为屏幕的占比
     */
    private void initTabLineWidth() {
        DisplayMetrics dpMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay()
                .getMetrics(dpMetrics);
        screenWidth = dpMetrics.widthPixels;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
                .getLayoutParams();
        lp.width = screenWidth / 5;
        mTabLineIv.setLayoutParams(lp);
    }

    /**
     * 重置颜色
     */
    private void resetTextView() {
        mtabpolTV.setTextColor(getResources().getColor(R.color.detianyiblue));
        mtabgameTV.setTextColor(getResources().getColor(R.color.detianyiblue));
        mtabanimTV.setTextColor(getResources().getColor(R.color.detianyiblue));
        mtabelTV.setTextColor(getResources().getColor(R.color.detianyiblue));
        mtaboriTV.setTextColor(getResources().getColor(R.color.detianyiblue));
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.index_sort_tv:
                showSpinWindow();
                break;
            case R.id.left_message:
                //进入私信
                if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                    Intent intent = new Intent(IndexActivity.this, InnerMessageActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.cover_user_photo:
                //进入个人信息
                if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                    duserimg = userimg.getDrawable();
                    Intent intent = new Intent(IndexActivity.this, UserinfoActivity.class);
                    intent.putExtra("userimg", ImgUtils.Drawable2Bytes(duserimg));
                    //设定onResume重新加载用户信息
                    IsReloadUserInfo = true;
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(IndexActivity.this, LoginAcitivity.class);
                    Toast.makeText(this, "请先注册", Toast.LENGTH_SHORT).show();
                    startActivity(intent);
                    this.finish();
                }
                break;
            case R.id.index_userimg_cover:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.index_username:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.index_search_iv:
                if (LoginMode == LoginConstants.LOGIN_GUEST) {
                    Toast.makeText(this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                } else {
                    ToastUtils.show(this, "未开放");
//                    Intent intent = new Intent(IndexActivity.this, SearchActivity.class);
//                    startActivity(intent);
                }
                break;
            case R.id.id_pol_tv:
                mPageVp.setCurrentItem(0);
                refreshCurrectItem();
                break;
            case R.id.id_ori_tv:
                mPageVp.setCurrentItem(1);
                refreshCurrectItem();
                break;
            case R.id.id_game_tv:
                mPageVp.setCurrentItem(2);
                refreshCurrectItem();
                break;
            case R.id.id_anim_tv:
                mPageVp.setCurrentItem(3);
                refreshCurrectItem();
                break;
            case R.id.id_el_tv:
                mPageVp.setCurrentItem(4);
                refreshCurrectItem();
                break;
        }
    }

    private void getnotice() {
        
        RequestParams params = new RequestParams();
        params.put("type", "all");
       
        asyncHttpClient.post(getString(R.string.serverurl) + getString(R.string.getnotice), params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    String s = new String(bytes, "utf-8");
                    final NoticeNormalMessageJsonObj json = GsonUtils.GsonToBean(s, NoticeNormalMessageJsonObj.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (json.getUnread() > 0) {
                                usermessage.setNotificationNumber(json.getUnread());
                            } else {
                                usermessage.setNotificationNumber(0);
                            }
                        }
                    });
                } catch (UnsupportedEncodingException e) {
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        usermessage.setNotificationNumber(0);
                    }
                });
                

            }
        });
    }

    /**
     * 侧滑菜单item选中事件
     */

    private class NacigateonItemSelectedLinstener implements NavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.nav_history:
                    if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                        item.setChecked(false);
//                        Intent intent1 = new Intent(IndexActivity.this, HistoryActivity.class);
//                        startActivity(intent1);
                        Toast.makeText(IndexActivity.this, "sorry，该功能还未开放，码农们都很怠惰呢,哎呀别打人家！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(IndexActivity.this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.nav_ori:
                    if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                        item.setChecked(false);
                        Intent intent2 = new Intent(IndexActivity.this, OriActivity.class);
                        startActivity(intent2);
                    } else {
                        Toast.makeText(IndexActivity.this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.nav_mark:
                    if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                        item.setChecked(false);
                        Intent intent3 = new Intent(IndexActivity.this, MarkActivity.class);
                        startActivity(intent3);
                    } else {
                        Toast.makeText(IndexActivity.this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.nav_collection:
                    if (LoginMode == LoginConstants.LOGIN_NORMAL) {
                        item.setChecked(false);
                        Intent intent4 = new Intent(IndexActivity.this, CollectionActivity.class);
                        startActivity(intent4);
                    } else {
                        Toast.makeText(IndexActivity.this, "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.nav_setting:
                    item.setChecked(false);
                    Intent intent5 = new Intent(IndexActivity.this, SettingsActivity.class);
                    startActivity(intent5);
                    break;
                case R.id.nav_suggestion:
                    item.setChecked(false);
                    Intent intent6 = new Intent(IndexActivity.this, SuggActivity.class);
                    startActivity(intent6);
                    break;
            }
            mDrawerLayout.closeDrawer(GravityCompat.START);
            return true;
        }
    }

    public void refreshCurrectItem() {
        int position = mPageVp.getCurrentItem();
        IndexFragment indexFragment = (IndexFragment) mFragmentList.get(position);
        indexFragment.SetSortMode(SortMode);
    }

    //注册广播接收器
    private void setupReceiver() {
        receiver=new MyNoticeReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.yugan.android.phone.NoticeMessageService");
        registerReceiver(receiver,filter);
    }

    @Override
    protected void onResume() {
        //如果用户信息需要重新加载就重新加载
        if (IsReloadUserInfo) {
            getuserinfo();
            //反置flag
            IsReloadUserInfo = false;
        }
        Nocation.getnotice(this,Nocation.NOTICE_ALL,asyncHttpClient,mhandler);
        
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        //卸载广播接收器
        unregisterReceiver(receiver);
        receiver=null;
        super.onDestroy();
    }

    /**
     * 广播接收器
     */
    private class MyNoticeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            LogUtils.e("广播已接受");
            final int count = (int) bundle.get("count");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    usermessage.setNotificationNumber(count);
                }
            });
        }
    }
}
